package com.nullpointer.xchatfinal.fragment;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.ImageOptions;
import com.nullpointer.xchatfinal.MainActivity;
import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.ViewImageActivity;
import com.nullpointer.xchatfinal.object.ChatType;
import com.nullpointer.xchatfinal.object.TargetChat;
import com.nullpointer.xchatfinal.object.User;
import com.nullpointer.xchatfinal.object.UserInfo.GenderType;
import com.nullpointer.xchatfinal.utils.Common;
import com.nullpointer.xchatfinal.utils.Utils;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;

public class ViewProfileFragment extends DialogFragment {

	private TextView tvName;
	// private TextView tvBirthday;
	private ImageView ivGender;
	private TextView tvStatus;
	private Button btAction;
	private GenderType gender;
	private final static String USER_KEY = "USER_KEY";
	private static final String IS_SHOW_SEND_MSG = "IS_SHOW_SEND_MSG";
	private static final String IS_LOAD_FROM_SERVER = "IS_LOAD_FROM_SERVER";
	private User user;
	private boolean isShowSendMsg = true;
	private boolean isLoadFromServer;
	private TextView tvId;
	private ImageView ivAvatar;

	private LinearLayout llInfo;
	private ProgressBar pbLoading;
	private TextView tvInfo;

	public static ViewProfileFragment newInstance(User user,
			boolean isShowSendMsg, boolean isLoadFromServer) {
		ViewProfileFragment f = new ViewProfileFragment();
		Bundle args = new Bundle();
		args.putString(USER_KEY, user.toJson());
		args.putBoolean(IS_SHOW_SEND_MSG, isShowSendMsg);
		args.putBoolean(IS_LOAD_FROM_SERVER, isLoadFromServer);
		f.setArguments(args);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String value = getArguments().getString(USER_KEY);
		if (value == null) {
			dismiss();
			return;
		}
		user = User.fromJsonToUser(value);
		if (user.getUserID() == null) {
			return;
		}
		isShowSendMsg = getArguments().getBoolean(IS_SHOW_SEND_MSG, true);
		isLoadFromServer = getArguments()
				.getBoolean(IS_LOAD_FROM_SERVER, false);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_view_profile, container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		// tvBirthday.setText(DataManager.getInstance(getActivity())
		// .getUserBirthday());
		if (isShowSendMsg) {
			btAction.setText("Send message");
		} else {
			btAction.setText("Close");
		}

		// load from server
		if (isLoadFromServer) {
			getUserFromServer();
			return;
		}
		hideInfo();
		initUser();

	}

	private void getUserFromServer() {
		btAction.setEnabled(false);
		ivAvatar.setVisibility(View.GONE);
		showInfo("loading...", true);
		QBUsers.getUser(user.getUserID(), new QBEntityCallbackImpl<QBUser>() {
			@Override
			public void onSuccess(QBUser qbuser, Bundle args) {
				user = Utils.convertQBUserToUser(qbuser);
				initUser();
				hideInfo();
			}

			@Override
			public void onError(List<String> errors) {
				showInfo("Can't load this profile, please try again!", true);
				btAction.setText("Close");
				isShowSendMsg = false;
				btAction.setEnabled(true);
			}
		});
	}

	private void initUser() {
		btAction.setEnabled(true);
		ivAvatar.setVisibility(View.VISIBLE);
		showAvatar(Utils.getSmallAvatarFacebook(user.getUserInfo()
				.getAvatarID()));
		tvName.setText(user.getName());
		tvStatus.setText(user.getUserInfo().getStatus());
		tvId.setText("Profile id: " + user.getUserID());
		gender = user.getUserInfo().getGender();
		if (gender == GenderType.FEMALE) {
			ivGender.setImageResource(R.drawable.ic_female);
		} else if (gender == GenderType.MALE) {
			ivGender.setImageResource(R.drawable.ic_male);
		} else if (gender == GenderType.ANY) {
			ivGender.setImageResource(R.drawable.ic_other);
		}
	}

	private void showAvatar(String url) {
		if (url == null) {
			ivAvatar.setImageResource(R.drawable.ic_no_avatar);
			return;
		}
		ImageOptions options = new ImageOptions();
		options.round = 5;
		options.fileCache = true;
		options.memCache = true;
		options.targetWidth = 96;
		options.fallback = R.drawable.ic_private_avatar;
		AQuery aq = new AQuery(getActivity());
		aq.id(ivAvatar).image(url, options);
	}

	private void setEvent() {
		btAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isShowSendMsg) {
					if (user.getUserID() == null) {
						dismiss();
						return;
					}
					TargetChat targetChat = new TargetChat(user);
					try {
						((MainActivity) getActivity()).showChat(targetChat);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				dismiss();

			}
		});

		ivAvatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String avatarLarge = Utils.getLargeAvatarFacebook(user
						.getUserInfo().getAvatarID());
				if (avatarLarge == null) {
					return;
				}
				Intent intent = new Intent(getActivity(),
						ViewImageActivity.class);
				intent.putExtra(Common.ExtraKey.IMAGE_URL, avatarLarge);
				getActivity().startActivity(intent);
			}
		});
	}

	private void findViewIds(View view) {
		tvName = (TextView) view.findViewById(R.id.tv_name);
		// tvBirthday = (TextView) view.findViewById(R.id.tv_birthday);
		tvStatus = (TextView) view.findViewById(R.id.tv_status);
		btAction = (Button) view.findViewById(R.id.bt_action);
		tvId = (TextView) view.findViewById(R.id.tv_id);
		ivGender = (ImageView) view.findViewById(R.id.iv_gender);
		ivAvatar = (ImageView) view.findViewById(R.id.iv_avatar);
		llInfo = (LinearLayout) view.findViewById(R.id.ll_info);
		pbLoading = (ProgressBar) view.findViewById(R.id.pb_loading);
		tvInfo = (TextView) view.findViewById(R.id.tv_info);
	}

	public void showInfo(String messgae, boolean isShowProgessbar) {
		llInfo.setVisibility(View.VISIBLE);
		tvInfo.setText(messgae);
		if (isShowProgessbar) {
			pbLoading.setVisibility(View.VISIBLE);
		} else {
			pbLoading.setVisibility(View.GONE);
		}
	}

	public void hideInfo() {
		llInfo.setVisibility(View.GONE);
	}
}
